<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/5/31
 * Time: 15:20
 */

namespace app\api\controller\android\v13;


use think\Controller;
use think\Request;
use app\api\model\AliPay;
use think\Db;
use app\api\model\Authority;
use think\Exception;

class Direct extends Controller
{
    protected $us;
    
    public function _initialize()
    {
        $this->us = Authority::check(1);
        
    }
    
    public function index()
    {
        $rows   = db('direct_salegood', config('database.zong'))
            ->join('direct_restricted_city', 'direct_restricted_city.direct_id=direct_salegood.direct_id', 'left')
            ->where('CASE
             WHEN direct_salegood.restricted_type=2 THEN direct_restricted_city.city_id ='.config('cityId').'
             WHEN direct_salegood.restricted_type=1  THEN  direct_restricted_city.city_id is null END')
            ->where('state', 0)
            ->order('sort desc')
            ->field('direct_salegood.trade_name,direct_salegood.icon,direct_salegood.type_name,direct_salegood.type,direct_salegood.direct_id')
            ->select();
        $result = array();
        foreach ($rows as $k => $v) {
            $result[$v['type']][] = $v;
        }
        
        foreach ($result as $k => $list) {
            $schemeTag['type']  = $k;
            $schemeTag['title'] = $list[0]['type_name'];
            $schemeTag['data']  = $result[$k];
            $tageList[]         = $schemeTag;
        }
        r_date($tageList, 200);
    }
    
    public function DirectInfo()
    {
        
        $data = Authority::param(['id']);
        
        $info = db('direct_salegood', config('database.zong'))
            ->join('direct_config', 'direct_config.direct_id=direct_salegood.direct_id', 'left')
            ->field('direct_salegood.trade_name,ifnull(direct_salegood.introduce,"") as direct_salegood,direct_salegood.log,direct_salegood.quantity,direct_config.price,direct_salegood.direct_id,direct_salegood.introduce,direct_config.direct_spec_unit')
            ->where('direct_salegood.direct_id', $data['id'])
            ->find();
        
        $info['log']  = empty($info['log']) ? [] : unserialize($info['log']);
        $info['unit'] = db('unit', config('database.zong'))->where('id', $info['direct_spec_unit'])->value('title');
        
        r_date($info, 200);
    }
    
    public function payDirect()
    {
        
        $data = Authority::param(['pay_type', 'id', 'number', 'order_id']);
        
        header("Content-type:text/html;charset=utf-8");
        $reoderSn = 'ls' . order_sn();;
        //获取支付方式
        $pay_type = $data['pay_type'];//微信支付 或者支付宝支付
        //获取支付金额
        
        $info = db('direct_salegood', config('database.zong'))
            ->join('direct_config', 'direct_config.direct_id=direct_salegood.direct_id', 'left')
            ->field('direct_salegood.trade_name,direct_config.price,direct_salegood.direct_id')
            ->where('direct_salegood.direct_id', $data['id'])
            ->find();
        
        $money = $info['price'] * $data['number'];

//        $money =10;
        //判断支付方式
        Db::connect(config('database.zong'))->startTrans();
        try {
            switch ($pay_type) {
                case 1;//如果支付方式为支付宝支付
                    //更新支付方式为支付宝
                    $type['pay_type'] = 'ali';
                    //实例化alipay类
                    $aliPay = new Alipay();
                    //异步回调地址
                    
                    $request = $aliPay->doPay($money, $reoderSn, $info['trade_name'], 'https://api-shopowner.yiniao.co/api/callback/alinotify?city=cd');
                    
                    
                    if (!empty($request) && $request['alipay_trade_precreate_response']['code'] == 10000) {
                        
                        $code_url            = $request['alipay_trade_precreate_response']['qr_code'];
                        $url['url']          = DOMAIN_SRC. 'qrcode.php?data=' . $code_url;
                        $url['out_trade_no'] = $request['alipay_trade_precreate_response']['out_trade_no'];
                    } else {
                        throw  new Exception($request);
                    }
                    
                    break;
                case 2;
                    require ROOT_PATH . 'extend/wxpay/WxPay.Api.php'; //引入微信支付
                    $input        = new \WxPayUnifiedOrder();
                    $config       = new \WxPayConfig();//配置参数
                    $paymoney     = $money; //测试写死
                    $out_trade_no = $reoderSn; //商户订单号(自定义)
                    $goods_name   = $info['trade_name'] . $paymoney . '元'; //商品名称(自定义)
                    $input->SetBody($goods_name);
                    $input->SetAttach($goods_name);
                    $input->SetOut_trade_no($out_trade_no);
                    $input->SetTotal_fee($paymoney * 100);//金额乘以100
                    $input->SetTime_start(date("YmdHis"));
                    $input->SetTime_expire(date("YmdHis", time() + 600));
                    $input->SetGoods_tag("test");
                    $input->SetNotify_url("https://api-shopowner.yiniao.co/api/callback/notify?city=cd"); //回调地址
                    $input->SetTrade_type("NATIVE");
                    $input->SetProduct_id("123456789");//商品id
                    $result = \WxPayApi::unifiedOrder($config, $input);
                    if ($result['return_code'] == 'SUCCESS') {
                        $code_url            = $result['code_url'];
                        $url['url']          = DOMAIN_SRC. 'qrcode.php?data=' . $code_url;
                        $url['out_trade_no'] = $out_trade_no;
                    } else {
                        throw  new Exception($result);
                        
                    }
                
            }
            $params = ['quantity' => $data['number'],
                'price' => $info['price'],
                'created_time' => time(),
                'name' => $info['trade_name'],
                'serial_number' => $reoderSn,
                'mode' => $pay_type,
                'order_id' => $data['order_id'],
                'direct_salegood_id' => $data['id'],
                'money' => $money,
                'company_id' =>db('company_config', config('database.zong'))->where('find_in_set(:id,store_list)', ['id' => $this->us['store_id']])->where('status', 1)->value('company_id')
            ];
            db('log', config('database.zong'))->insert(['type' => 28, 'msg' => '直售商品', 'content' => json_encode($params), 'created_at' => time()]);
            Db::connect(config('database.zong'))->table('direct_payment_record')->insert($params);
            Db::connect(config('database.zong'))->commit();
            r_date($url, 200);
        } catch (Exception $exception) {
            Db::connect(config('database.zong'))->rollback();
            r_date(null, 300, $exception->getMessage());
        }
        
        
    }
    /*
     * 退款
     */
    public function refund()
    {
        
        $data = Authority::param(['id', 'reason']);
        header("Content-type:text/html;charset=utf-8");
        $reoderSn = 'ls' . order_sn();;
        //获取支付金额
        $info = db('direct_payment_record', config('database.zong'))
            ->join('direct_order', 'direct_payment_record.serial_number=direct_order.payNo', 'left')
            ->join('order', 'order.order_id=direct_order.order_id', 'left')
            ->join('order_info', 'order_info.order_id=order.order_id', 'left')
            ->field('direct_payment_record.serial_number,direct_payment_record.mode,(direct_payment_record.price*direct_payment_record.quantity) as money,direct_payment_record.name,direct_payment_record.out_trade_no,direct_payment_record.order_id,CONCAT(order_info.province,order_info.city,order_info.county,order.addres) as address,direct_payment_record.purchase_id,direct_order.id')
            ->where('purchase_id', $data['id'])
            ->find();
        //判断支付方式
        Db::connect(config('database.zong'))->startTrans();
        try {
            switch ($info['mode']) {
                case 1;//如果支付方式为支付宝支付
                    //更新支付方式为支付宝
                    $type['pay_type'] = 'ali';
                    //实例化alipay类
                    $aliPay = new Alipay();
                    //异步回调地址
                    $request = $aliPay->TuiPay($info['money'], $info['serial_number'], $info['out_trade_no'], $info['name']);
                    
                    if (!empty($request) && $request['alipay_trade_refund_response']['code'] == 10000 && $request['alipay_trade_refund_response']['msg'] == "Success") {
                        Db::connect(config('database.zong'))->table('direct_payment_record')->where('purchase_id', $data['id'])->update(['state' => 2, 'refund_time' => time(), 'reason' => $data['reason']]);
                        
                        U8cMasters('收到' . $info['address'] . $info['name'] . '打压完成', '-' . sprintf('%.2f', ($info['money'])), $info['order_id'], 23, 12, 1, 0,$data['id']);
                    } else {
                        throw  new Exception($request['alipay_trade_refund_response']['msg']);
                    }
                    break;
                case 2;
                    require ROOT_PATH . 'extend/wxpay/WxPay.Api.php'; //引入微信支付
                    $input        = new \WxPayRefund();
                    $config       = new \WxPayConfig();//配置参数
                    $paymoney     = $info['money']; //测试写死
                    $out_trade_no = $info['serial_number']; //商户订单号(自定义)
                    $input->SetOut_trade_no($out_trade_no);
                    $input->SetTotal_fee($paymoney * 100);//金额乘以100
                    $input->SetRefund_fee($paymoney * 100);//金额乘以100
                    $input->SetOut_refund_no($info['out_trade_no']);//金额乘以100
                    $input->SetOp_user_id(131);//金额乘以100
                    $result = \WxPayApi::refund($config, $input);
                    if ($result['return_code'] == 'SUCCESS') {
                        Db::connect(config('database.zong'))->table('direct_payment_record')->where('purchase_id', $data['id'])->update(['state' => 2, 'refund_time' => time(), 'reason' => $data['reason']]);
                        $def1 = '-'.sprintf('%.2f', $info['money'] * 0.0054);
                        U8cMasters('收到' . $info['address'] . $info['name'] . '打压完成','-' . sprintf('%.2f', ($info['money'])), $info['order_id'], 23, 2, 1, $def1,$data['id']);
                    } else {
                        throw  new Exception($result['return_code']);
                    }
                
            }
            
            if (!empty($info['id'])) {
                Db::connect(config('database.zong'))->table('direct_order')->where('id', $info['id'])->update(['state' => 2]);
                $examine = Db::connect(config('database.zong'))->table('direct_examine')->where('direct_id', $info['id'])->find();
                if (!empty($examine)) {
                    Db::connect(config('database.zong'))->table('direct_examine')->where('direct_id', $info['id'])->update(['state' => 2, 'refund_time' => time()]);
                }
            }
            Db::connect(config('database.zong'))->commit();
            r_date(null, 200);
        } catch (Exception $exception) {
            Db::connect(config('database.zong'))->rollback();
            r_date(null, 300, $exception->getMessage());
        }
        
        
    }
    public function orderQuery()
    {
        $data     = Authority::param(['pay_type', 'out_trade_no']);
        $order_id = Db::connect(config('database.zong'))->table('direct_payment_record')
            ->join('direct_order', 'direct_payment_record.serial_number=direct_order.payNo', 'left')
            ->join('order_info', 'order_info.order_id=direct_payment_record.order_id', 'left')
            ->join('order', 'order.order_id=direct_payment_record.order_id', 'left')
            ->where('direct_payment_record.serial_number', $data['out_trade_no'])
            ->field('CONCAT(order_info.province,order_info.city,order_info.county,order.addres) as address,direct_payment_record.name,direct_payment_record.order_id,direct_payment_record.price,direct_payment_record.quantity,direct_payment_record.state,direct_payment_record.purchase_id')
            ->find();
        
        if($order_id['state']==1){
            r_date(1, 200);
        }
        if ($data['pay_type'] == 2) {
            require ROOT_PATH . 'extend/wxpay/WxPay.Api.php'; //引入微信支付
            $config = new \WxPayConfig();//配置参数
            $input  = new \WxPayUnifiedOrder();
            $input->SetOut_trade_no($data['out_trade_no']);
            $result = \WxPayApi::orderQuery($config, $input);
            if ($result['return_code'] == 'SUCCESS') {
                if (isset($result['trade_state']) && $result['trade_state'] == 'SUCCESS') {
                    Db::connect(config('database.zong'))->table('direct_payment_record')->where('serial_number', $data['out_trade_no'])->update(['state' => 1, 'payment_time' => time(), 'out_trade_no' => $result['transaction_id']]);
                    $def1 = sprintf('%.2f', $order_id['price'] * $order_id['quantity'] * 0.0054);
                    if(!empty($order_id['purchase_id'])) {
                        U8cMasters('收到' . $order_id['address'] . $order_id['name'] . '打压完成', sprintf('%.2f', ($order_id['price'] * $order_id['quantity'])), $order_id['order_id'], 23, 2, 1, $def1, $order_id['purchase_id']);
                    }
                    r_date(1, 200);
                } else {
                    r_date(2, 200);
                }
            } else {
                journal(['url' => $data['out_trade_no'], 'data' => $result], 1);
            }
        } else {
            $aliPay     = new Alipay();
            $resultCode = $aliPay->queryPay($data['out_trade_no']);
            if (!empty($resultCode) && $resultCode['alipay_trade_query_response']['code'] == 10000) {
                if ($resultCode['alipay_trade_query_response']['trade_status'] == 'TRADE_SUCCESS') {
                    Db::connect(config('database.zong'))->table('direct_payment_record')->where('serial_number', $data['out_trade_no'])->update(['state' => 1, 'payment_time' => time(), 'out_trade_no' => $resultCode['alipay_trade_query_response']['trade_no']]);
                    if(!empty($order_id['purchase_id'])){
                        U8cMasters('收到' . $order_id['address'] . $order_id['name'] . '打压完成', sprintf('%.2f', ($order_id['price'] * $order_id['quantity'])), $order_id['order_id'], 23, 12, 1, 0,$order_id['purchase_id']);
                    }
                    
                    r_date(1, 200);
                } else {
                    r_date(2, 200);
                }
                
            } else {
                r_date(2, 200);
            }
            
            
        }
        
        
    }
    
    public function suppress()
    {
        $data = Authority::param(['user_id', 'time', 'order_id', 'type', 'payNo']);
        if (empty($data['user_id'])) {
            r_date(null, 300, '缺少参数');
        }
        if (empty($data['order_id'])) {
            r_date(null, 300, '缺少参数');
        }
        if (empty($data['type'])) {
            r_date(null, 300, '缺少参数');
        }
        if (empty($data['payNo'])) {
            r_date(null, 300, '缺少参数');
        }
        $direct_order=db('direct_order', config('database.zong'))->where(['payNo' => $data['payNo'], 'city_id' => config('cityId')])->find();
        $info=0;
        if(empty($direct_order)){
            $info = db('direct_order', config('database.zong'))->insertGetId([
                'user_id' => $data['user_id'],
                'created_time' => time(),
                'order_id' => $data['order_id'],
                'type' => $data['type'],
                'distribute_time' => strtotime($data['time']),
                'payNo' => $data['payNo'],
                'city_id' => config('cityId'),
            
            ]);
        }
        
        r_date($info, 200);
    }
    
    public function suppressFinished()
    {
        $data         = Authority::param(['result', 'id', 'remark','picture']);
        $direct_order = Db::connect(config('database.zong'))->table('direct_order')->where('id', $data['id'])->find();
        $info         = 0;
        db()->startTrans();
        try {
            if ($direct_order['state'] != 1) {
                
                $info = db('direct_order', config('database.zong'))->where('id', $data['id'])->update([
                    'result' => $data['result'],
                    'complete_time' => time(),
                    'state' => 1,
                    'describe' => $data['remark'],
                    'picture' =>!empty($data['picture']) ? serialize(json_decode($data['picture'], true)) : '',//图片
                
                ]);
                
                
                $order_id = Db::connect(config('database.zong'))->table('direct_order')->where('direct_order.id', $data['id'])
                    ->join('direct_payment_record', 'direct_order.payNo=direct_payment_record.serial_number', 'left')
                    ->join('order', 'order.order_id=direct_order.order_id', 'left')
                    ->join('order_info', 'order_info.order_id=direct_order.order_id', 'left')
                    ->join('direct_salegood', 'direct_salegood.direct_id=direct_payment_record.direct_salegood_id', 'left')
                    ->join('direct_config', 'direct_config.direct_id=direct_salegood.direct_id', 'left')
                    ->field('direct_order.order_id,direct_payment_record.price,direct_payment_record.name,direct_payment_record.quantity,direct_config.commission,direct_order.type,direct_order.user_id,CONCAT(order_info.province,order_info.city,order_info.county,order.addres) as address,direct_payment_record.mode')
                    ->find();
                $commission=$order_id['commission'] * $order_id['quantity'];
                if($commission==0 || empty($commission)){
                    throw  new  Exception('提成金额错误');
                }
                Db::connect(config('database.zong'))->table('direct_examine')->insert([
                    'direct_id' => $data['id'],
                    'type' => $order_id['type'],
                    'user_id' => $order_id['user_id'],
                    'city_id' => config('cityId'),
                    'commission' =>$commission,
                    'created_time' => time(),
                ]);
                
                db('order')->where('order_id', $order_id['order_id'])->update(['direct' => $data['id']]);
                sendOrder($order_id['order_id']);
            }
            Db::connect(config('database.zong'))->commit();
            r_date(null, 200);
        } catch (Exception $e) {
            Db::connect(config('database.zong'))->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
    }
    
    
    public function suppressList()
    {
        $data = Authority::param(['page', 'limit', 'time']);
        
        $direct_order = db('direct_order', config('database.zong'))
            ->join('order', 'order.order_id=direct_order.order_id', 'left')
            ->join('direct_examine', 'direct_order.id=direct_examine.direct_id', 'left')
            ->join('direct_payment_record', 'direct_order.payNo=direct_payment_record.serial_number', 'left')
//            ->join('direct_salegood', 'direct_salegood.direct_id=direct_payment_record.direct_salegood_id', 'left')
//            ->join('direct_config', 'direct_config.direct_id=direct_salegood.direct_id and direct_config.city=' . config('cityId'), 'left')
            ->field('order.addres,direct_order.state,FROM_UNIXTIME(direct_order.distribute_time,"%Y-%m-%d %H:%i:%s") as distribute_time,FROM_UNIXTIME(direct_order.complete_time,"%Y-%m-%d %H:%i:%s") as complete_time,direct_order.id,CONCAT(direct_payment_record.name,direct_payment_record.quantity,"次") as name,direct_examine.commission');
        if (!empty($data['time'])) {
            $start = strtotime(date('Y-m-01 00:00:00', strtotime($data['time'])));//获取指定月份的第一天
            $end   = strtotime(date('Y-m-t 23:59:59', strtotime($data['time']))); //获取指定月份的最后一天
            $direct_order->whereBetween('complete_time', [$start, $end]);
        }
        $info['data'] = $direct_order->page($data['page'], $data['limit'])
            ->where('direct_order.user_id', $this->us['user_id'])
            ->where('direct_order.state', '<>',2)
            ->order('direct_order.state asc,direct_order.distribute_time desc')
            ->select();
        $direct_count = db('direct_order', config('database.zong'))
            ->join('direct_payment_record', 'direct_order.payNo=direct_payment_record.serial_number', 'left')
            ->join('direct_examine', 'direct_order.id=direct_examine.direct_id', 'left')
//            ->join('direct_salegood', 'direct_salegood.direct_id=direct_payment_record.direct_salegood_id', 'left')
//            ->join('direct_config', 'direct_config.direct_id=direct_salegood.direct_id and direct_config.city=' . config('cityId'), 'left')
            ->join('order', 'order.order_id=direct_order.order_id', 'left');
        if (!empty($data['time'])) {
            $start = strtotime(date('Y-m-01 00:00:00', strtotime($data['time'])));//获取指定月份的第一天
            $end   = strtotime(date('Y-m-t 23:59:59', strtotime($data['time']))); //获取指定月份的最后一天
            $direct_count->whereBetween('complete_time', [$start, $end]);
        }
        $info['count']      = $direct_count->where('direct_order.user_id', $this->us['user_id'])
            ->where('direct_order.state', '<>',2)
            ->count();
//        $info['commission'] = 0;
        $info['commission'] = array_sum(array_column($info['data'], 'commission'));
//       foreach ($info['data'] as $i){
//           if($i['state']==1){
//               $info['commission']+=($i['commission']);
//           }
//
//       }
        
        r_date($info, 200);
    }
    
    
    public function PurchaseRecord()
    {
        
        $data         = Authority::param(['page', 'limit', 'order_id']);
        $info['data'] = db('direct_payment_record', config('database.zong'))
            ->join('order', 'order.order_id=direct_payment_record.order_id', 'left')
            ->join('direct_salegood', 'direct_salegood.direct_id=direct_payment_record.direct_salegood_id', 'left')
            ->join('direct_config', 'direct_config.direct_id=direct_salegood.direct_id', 'left')
            ->join('direct_order', 'direct_order.payNo=direct_payment_record.serial_number', 'left')
            ->field('direct_payment_record.quantity,direct_payment_record.name,direct_payment_record.price,FROM_UNIXTIME(direct_payment_record.created_time,"%Y-%m-%d %H:%i:%s") as created_time,FROM_UNIXTIME(direct_payment_record.refund_time,"%Y-%m-%d %H:%i:%s") as refund_time,direct_payment_record.reason,FROM_UNIXTIME(direct_payment_record.payment_time,"%Y-%m-%d %H:%i:%s") as payment_time,FROM_UNIXTIME(direct_order.distribute_time,"%Y-%m-%d %H:%i:%s") as distributeTime,purchase_id,order.order_id,direct_order.type,direct_order.user_id,direct_payment_record.direct_salegood_id as directId,(case  when ifNull(direct_order.id,0) !=0  and direct_payment_record.state=1 and direct_order.state=0  then 4 when ifNull(direct_order.id,0)=0  and direct_payment_record.state=1 then 3 when ifNull(direct_order.id,0) !=0 and direct_payment_record.state=1 and direct_order.state=1 then 1  when ifNull(direct_order.id,0)=0  and direct_payment_record.state=0 then 0 when  direct_payment_record.state=2 then 2 end ) as state,direct_payment_record.serial_number as payNo')
            ->page($data['page'], $data['limit'])
            ->where(function ($quer){
                $quer->where('direct_payment_record.state', 1)->whereor('direct_payment_record.state', 2);
            })
            ->where('direct_payment_record.order_id', $data['order_id'])
            ->where('order.assignor', $this->us['user_id'])
            ->order('direct_payment_record.created_time desc')
            ->select();
        foreach ($info['data'] as $k => $item) {
            if ($item['type'] == 1) {
                $info['data'][$k]['username'] =!empty($item['user_id'])? db('user')->where('user_id', $item['user_id'])->value('username') . '（店长）':'';
            } else {
                $info['data'][$k]['username'] =!empty($item['user_id'])?db('app_user', config('database.db2'))->where('id', $item['user_id'])->value('username') . '（师傅）':'';
            }
            
        }
        $info['count'] = db('direct_payment_record', config('database.zong'))
            ->join('order', 'order.order_id=direct_payment_record.order_id', 'left')
            ->join('direct_salegood', 'direct_salegood.direct_id=direct_payment_record.direct_salegood_id', 'left')
            ->join('direct_config', 'direct_config.direct_id=direct_salegood.direct_id', 'left')
            ->join('direct_order', 'direct_order.payNo=direct_payment_record.serial_number', 'left')
            ->where(function ($quer){
                $quer->where('direct_payment_record.state', 1)->whereor('direct_payment_record.state', 2);
            })
            ->where('direct_payment_record.order_id', $data['order_id'])
            ->where('order.assignor', $this->us['user_id'])
            ->count();
        r_date($info, 200);
    }
    
    public function userID()
    {
        $date    = Authority::param(['title']);
        $exp     = new \think\db\Expression('(app_user.store_id=' . $this->us['store_id'] . ') DESC, app_user.id desc');
        $appUser = db('app_user', config('database.db2'))
            ->join(config('database')['database'] . '.store', 'store.store_id=app_user.store_id', 'left')
            ->where('app_user.status', 1)
            ->where('app_user.checked', 1)
            ->field('app_user.id as user_id,CONCAT(app_user.username,"(",store.store_name,")") as username')
            ->order($exp)
            ->select();
        foreach ($appUser as $k => $item) {
            $appUser[$k]['type'] = 2;
        };
        $user['user_id']  = $this->us['user_id'];
        $user['username'] = $this->us['username'] . "(本人)";
        $user['type']     = 1;
        $user1[]          = $user;
        $data             = array_merge($user1, $appUser);
        if (isset($date['title']) && $date['title'] != '') {
            $list = array();        // 匹配后的结果
            
            $search_str = $date['title'];        // 搜索的字符串
            foreach ($data as $key => $val) {
                
                if (strstr($val['username'], $search_str) !== false) {
                    array_push($list, $val);
                }
            }
            $data = $list;
        }
        
        
        r_date($data, 200);
    }
}